import os
import shutil

from flask import Blueprint, send_file, make_response, request
import time
import setting
from server.module.fileManager.FileTree import ShareFileTree
from server.utils.mylog import mylog

fields = Blueprint('files', __name__, url_prefix=setting.prefixURL + '/fields/')


@fields.route('upload', methods=['post'])
def fileReceiver():
    t = request.args.get('t')
    if t == 'u':
        file_dir = setting.UploadPath
    elif t == 'd':
        file_dir = setting.DownloadPath
    else:
        return make_response('上传失败，请求路径错误', 403)

    # 从表单的file字段获取文件，myfile为该表单的name值
    a = request.files.get('files')
    if a is None:
        print("ERROR>>>[4032]未接受到文件 | " + request.path)
        return make_response('上传失败，未接收到文件', 400)
    if os.path.isfile(os.path.join(file_dir, a.filename)):
        return make_response('上传失败，存在同名文件', 400)  # 存在同名文件
    else:
        a.save(os.path.join(file_dir, a.filename))
        mylog.data(f"[{request.remote_addr}]Received file: {a.filename}")
        return make_response('上传成功')


@fields.route('delete', methods=['post'])
def deleteFiles():
    target = request.data.decode()
    target = target.lstrip('/fields/download/')
    mylog.info(f"[{request.remote_addr}]Deleted file: {target}")
    os.remove(
        os.path.join(setting.DownloadPath, target)
    )
    return 'ok'


@fields.route('tree', methods=['get'])
def fileTree():
    o_fileTree = ShareFileTree()
    json_fileTree_result = o_fileTree.print_tree()
    response = make_response()
    response.content_type = 'application/json'
    response.data = json_fileTree_result
    return response


@fields.route('download/<path:path>', methods=['get'])
def downloads(path):
    mylog.info(f'[{request.remote_addr}]Downloading file: {path}')
    return send_file(os.path.join(setting.DownloadPath, path))


@fields.route('clearupload', methods=['get'])
def clearupload():
    mylog.warn(f'[{request.remote_addr}]Clear Upload')
    shutil.rmtree(setting.UploadPath)
    os.mkdir(setting.UploadPath)
    return 'ok'
